package com.dtsz.m2.ui.home;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.android.volley.Request;
import com.bumptech.glide.Glide;
import com.cxy.library.entity.BannerEntity;
import com.cxy.library.iutils.IBannerBaseAdapter;
import com.cxy.library.view.BannerView;
import com.dtsz.m2.R;
import com.dtsz.m2.config.UrlConfig;
import com.dtsz.m2.ui.activity.EcologyActivity;
import com.dtsz.m2.ui.activity.EcologyOrderActivity;
import com.dtsz.m2.ui.activity.LoginActivity;
import com.dtsz.m2.ui.activity.NoticeActivity;
import com.dtsz.m2.ui.adapter.EcologyAdatper;
import com.dtsz.m2.ui.adapter.OrderAdatper;
import com.dtsz.m2.ui.base.BaseFragment;
import com.dtsz.m2.ui.model.Ecology;
import com.dtsz.m2.ui.model.EcologyOrder;
import com.dtsz.m2.ui.model.Notice;
import com.dtsz.m2.ui.model.RegisterVo;
import com.dtsz.m2.utils.RegluarUtils;
import com.dtsz.m2.utils.StringUtils;
import com.dtsz.m2.volley.VolleyApplication;
import com.dtsz.m2.volley.attribute.AUAttributeUtils;
import com.dtsz.m2.volley.state.HUCState;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;


public class HomeFragment extends BaseFragment {
    public static final RegisterVo REGISTER_VO = new RegisterVo();
    private BannerView ivBanner;
    private TextView tvTitle;
    private GridView gvStq;
    private ListView lvOrder;

    private OrderAdatper orderAdatper;
    private EcologyAdatper ecologyAdatper;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        root.findViewById(R.id.ll_notice).setOnClickListener(this);
        root.findViewById(R.id.ll_gesture).setOnClickListener(this);
        root.findViewById(R.id.ll_ecology_order).setOnClickListener(this);
        ivBanner = root.findViewById(R.id.iv_banner);
        tvTitle = root.findViewById(R.id.tv_title);
        gvStq = root.findViewById(R.id.gv_stq);
        lvOrder = root.findViewById(R.id.lv_order);
        gvStq.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 1) {
                    String oaid = VolleyApplication.getOaid();
                    String appkey = "85ffd5eb52460ec9de";
                    String uid = "920";//uid
                    String type = "null";//cpl 游戏 gaoe 截图试玩 为null表示全部
                   // new JieTuAd(getActivity(), null, appkey, uid, type, false, oaid);
                } else {
                    sendIntent(getActivity(), EcologyActivity.class);
                }

            }
        });
        return root;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (hucRequestInterfase != null) {
            hucRequestInterfase.cancelAll();
        }

    }

    @Override
    public void onErrorLogin(int inputType) {
        super.onErrorLogin(inputType);
        setSharedPreferences("tokenRSA", "token001");
        getActivity().finish();
        sendIntent(getActivity(), LoginActivity.class);
    }

    @Override
    public void onStart() {
        super.onStart();
        String phone = getSharedPreferences("phone");
        if (StringUtils.isEmpty(phone)) {
            getBindPhone();
        } else {
            String card = getSharedPreferences("card");
            if (StringUtils.isEmpty(card)) {
                getBindCard();
            }
        }
        initData();
        // initBanner();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_notice:
                sendIntent(getActivity(), NoticeActivity.class);
                break;
            case R.id.ll_ecology_order:
                sendIntent(getActivity(), EcologyOrderActivity.class);
                break;
            case R.id.ll_gesture:
                sendIntent(getActivity(), EcologyActivity.class);
                break;
        }
    }

    public void initData() {
        pageVo.setType("3");
        hucRequestInterfase.executeStr(this, String.class,
                HUCState.HUC_REQEUST_CODE_1, Request.Method.POST, UrlConfig.HOME_URL,
                hucParameInterfase.getRequestParameter(pageVo), true);
    }

    @Override
    public void onSuccessfulStrType(int inputType, Object response) {
        super.onSuccessfulStrType(inputType, response);
        switch (inputType) {
            case HUCState.HUC_REQEUST_CODE_1:
                String responseStr = (String) response;
                try {
                    JSONObject json = new JSONObject(responseStr);
                    String ecologyOrders = json.getString("ecologyOrders");
                    String notice = json.getString("notice");
                    String ecologs = json.getString("ecologs");
                    String banner = json.getString("banner");
                    List<BannerEntity> bannerEntity = (List<BannerEntity>) parseJsonList(BannerEntity.class, banner, false);
                    Notice notice1 = (Notice) parseJsonObject(Notice.class, new JSONObject(notice));
                    List<Ecology> ecologyList = (List<Ecology>) parseJsonList(Ecology.class, ecologs, false);
                    List<EcologyOrder> ecologyOrderList = (List<EcologyOrder>) parseJsonList(EcologyOrder.class, ecologyOrders, false);
//                    String url = null;
//                    if (bannerEntity != null) {
//                        FragmentActivity fragmentActivity = getActivity();
//                        if (fragmentActivity != null) {
//                            Glide.with(getActivity()).load(bannerEntity.getBarAddress()).into(ivBanner);
//                        }
//                        url = bannerEntity.getBarUrl();
//                    }
//                    if (!StringUtils.isEmpty(url) && !"0".equals(url)) {
//                        final String finalUrl = url;
//                        ivBanner.setOnClickListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                Uri uri = Uri.parse(finalUrl);
//                                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//                                startActivity(intent);
//                            }
//                        });
//                    }
                    if (bannerEntity != null && bannerEntity.size() > 0) {
                        LoopPhotoAdapter loopPhotoAdapter = new LoopPhotoAdapter(getActivity(), bannerEntity);
                        if (bannerEntity.size() <= 1) {
                            ivBanner.setRl_point_group(View.GONE);
                        }
                        ivBanner.setAdapter(loopPhotoAdapter);
                    }
                    if (notice1 != null) {
                        tvTitle.setText(notice1.getNotTitle());
                    }
                    orderAdatper = new OrderAdatper(getActivity(), ecologyOrderList, R.layout.item_order);
                    lvOrder.setAdapter(orderAdatper);
                    //setListViewHeightBasedOnChildren(lvOrder);
                    ecologyAdatper = new EcologyAdatper(getActivity(), ecologyList, R.layout.item_gridview);
                    gvStq.setAdapter(ecologyAdatper);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                break;
            case HUCState.HUC_REQEUST_CODE_2:
                String msg = (String) response;
                if ("绑定成功".equals(msg)) {
                    setSharedPreferences("phone", etPhone.getText().toString());
                    alertDialog1.dismiss();
                    String card = getSharedPreferences("card");
                    if (StringUtils.isEmpty(card)) {
                        getBindCard();
                    }
                }
                showToast(msg);
                break;
            case HUCState.HUC_REQEUST_CODE_6:
                String msgcard = (String) response;
                if ("绑定成功".equals(msgcard)) {
                    setSharedPreferences("card", etPhone.getText().toString());
                    alertDialog1.dismiss();
                }
                showToast(msgcard);
                break;
            case HUCState.HUC_REQEUST_CODE_5:
                if (response instanceof List) {
                    List<com.cxy.library.entity.BannerEntity> bannerEntityList = (List<com.cxy.library.entity.BannerEntity>) response;
                    if (bannerEntityList != null && bannerEntityList.size() > 0) {
                        uploadHeadImage(bannerEntityList.get(0).getBarAddress(), bannerEntityList.get(0).getBarUrl());
                    }
                }
                break;
        }
        loadDismiss();
    }


    private Object parseJsonObject(Class<?> class1, JSONObject jsonObject) {
        List<String> attr = AUAttributeUtils.getInstance().getAttributeName(class1,
                false);
        Object obj = null;
        try {
            obj = class1.newInstance();
            for (int j = 0; j < attr.size(); j++) {
                String setName = attr.get(j);
                String setValue = jsonObject.optString(setName);
                setName = "set" + setName.substring(0, 1).toUpperCase()
                        + setName.substring(1);
                Method method = class1.getDeclaredMethod(setName, String.class);
                method.setAccessible(true);
                method.invoke(obj, setValue);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return obj;
    }

    public Object parseJsonList(Class<?> class1, String jsonStr, boolean isFlag) {
        List<Object> list = new ArrayList<Object>();
        try {
            JSONArray array = new JSONArray(jsonStr);
            int arrayLen = array.length();
            if (array != null || arrayLen > 0) {
                for (int i = 0; i < arrayLen; i++) {
                    JSONObject jsonObject = array.getJSONObject(i);
                    Object obj = parseJsonObject(class1, jsonObject);
                    if (arrayLen == 1 && isFlag) {
                        return obj;
                    }
                    list.add(obj);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    AlertDialog alertDialog1;
    EditText etPhone, etPhoneEnd;

    private void getBindPhone() {
        //判断是否绑定姓名
        AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
        // dialog.setTitle("绑定姓名");
        View root = LayoutInflater.from(getActivity()).inflate(R.layout.item_bind_phone, null);
        dialog.setView(root);
        etPhone = root.findViewById(R.id.et_phone);
        etPhoneEnd = root.findViewById(R.id.et_phone_end);
        root.findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone = etPhone.getText().toString();
                if (!RegluarUtils.isMobile(phone)) {
                    showToast("手机号码格式错误");
                    return;
                }
                String phoneEnd = etPhoneEnd.getText().toString();
                if (!phone.equals(phoneEnd)) {
                    showToast("两次手机号码不一致");
                    return;
                }
                getBindPhoneUrl(phone);
            }
        });
        alertDialog1 = dialog.create();
        alertDialog1.getWindow().setBackgroundDrawableResource(R.drawable.radius20);
        alertDialog1.setCancelable(false);
        alertDialog1.show();
    }

    private void getBindCard() {
        //判断是否绑定姓名
        AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
        // dialog.setTitle("绑定姓名");
        View root = LayoutInflater.from(getActivity()).inflate(R.layout.item_bind_card, null);
        dialog.setView(root);
        etPhone = root.findViewById(R.id.et_phone);
        etPhoneEnd = root.findViewById(R.id.et_phone_end);
        root.findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone = etPhone.getText().toString();
                if (!StringUtils.isIDNumber(phone)) {
                    showToast("身份证号证格式错误");
                    return;
                }
                String phoneEnd = etPhoneEnd.getText().toString();
                if (!phone.equals(phoneEnd)) {
                    showToast("两次身份证号不一致");
                    return;
                }
                getBindPhoneUrl(phone);
            }
        });
        alertDialog1 = dialog.create();
        alertDialog1.getWindow().setBackgroundDrawableResource(R.drawable.radius20);
        alertDialog1.setCancelable(false);
        alertDialog1.show();
    }

    public void getBindPhoneUrl(String phone) {
        RegisterVo registerVo = new RegisterVo();
        registerVo.setToken(pageVo.getToken());
        loading();
        if (phone.length() == 11) {
            registerVo.setPhone(phone);
            hucRequestInterfase.executeStr(this, String.class,
                    HUCState.HUC_REQEUST_CODE_2, Request.Method.POST, UrlConfig.BINDPHONE_URL,
                    hucParameInterfase.getRequestParameter(registerVo), true);
        } else {
            registerVo.setBuCard(phone);
            hucRequestInterfase.executeStr(this, String.class,
                    HUCState.HUC_REQEUST_CODE_6, Request.Method.POST, UrlConfig.BINDCARD_URL,
                    hucParameInterfase.getRequestParameter(registerVo), true);
        }
    }

    private void initBanner() {
        pageVo.setType("8");
        hucRequestInterfase.executeStr(this, com.cxy.library.entity.BannerEntity.class,
                HUCState.HUC_REQEUST_CODE_5, Request.Method.POST, UrlConfig.BANNER_URL,
                hucParameInterfase.getRequestParameter(pageVo), false);
    }
    ///弹出广告

    /**
     * 上传头像
     */
    private void uploadHeadImage(String url, final String address) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_banner, null);
        TextView btnCancel = view.findViewById(R.id.tv_delete);
        ImageView ivImage = view.findViewById(R.id.iv_image);
        Glide.with(getActivity()).load(url).into(ivImage);
        final PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(getResources().getDrawable(android.R.color.transparent));
        popupWindow.setOutsideTouchable(true);
        View parent = LayoutInflater.from(getActivity()).inflate(R.layout.activity_identification, null);
        popupWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
        //popupWindow在弹窗的时候背景半透明
        final WindowManager.LayoutParams params = getActivity().getWindow().getAttributes();
        params.alpha = 0.5f;
        getActivity().getWindow().setAttributes(params);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                params.alpha = 1.0f;
                getActivity().getWindow().setAttributes(params);
            }
        });

//        btnCarema.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (!(ActivityCompat.checkSelfPermission(IdentificationActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) ||
//                        !(ActivityCompat.checkSelfPermission(IdentificationActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) ||
//                        !(ActivityCompat.checkSelfPermission(IdentificationActivity.this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) ||
//                        !(ActivityCompat.checkSelfPermission(IdentificationActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) {
//                    //没有权限，申请权限
//                    String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.READ_EXTERNAL_STORAGE};
//                    //申请权限，其中RC_PERMISSION是权限申请码，用来标志权限申请的
//                    ActivityCompat.requestPermissions(IdentificationActivity.this, permissions, WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
//
//                } else {
//                    //跳转到调用系统相机
//                    gotoCamera();
//                }
//                popupWindow.dismiss();
//            }
//        });
        ivImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!"0".equals(address)) {
                    sendUrl(address);
                }
            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }


    class LoopPhotoAdapter implements IBannerBaseAdapter {
        Context context;
        List<BannerEntity> data;

        public LoopPhotoAdapter(Context context, List<BannerEntity> entities) {//构造方法
            this.context = context;
            data = entities;
        }

        @Override
        public void loadImage(String url, ImageView imageView) {//加载图片
            if (context != null) {
                Glide.with(context).load(url).into(imageView);
            }
        }

        @Override
        public int setItemCount() {//数据个数
            return data.size();
        }

        @Override
        public List<com.cxy.library.entity.BannerEntity> setData() {//设置数据
            return data;
        }

        @Override
        public void onItemClick(int position) {//点击事件
            com.cxy.library.entity.BannerEntity bannerEntity = data.get(position);
            String url = bannerEntity.getBarUrl();
            if (!"0".equals(url)) {
                sendUrl(url);
            }

        }
    }


}
